package com.zhdl.network.motor.after;

import cn.hutool.core.util.HexUtil;
import com.project.command.instruction.strategy.abs.AbsAfterControlCommand;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.network.modbus.dto.ModbusDto;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service(MotorAfterService.MOTOR_AFTER_SERVICE)
public class MotorAfterService extends AbsAfterControlCommand<ModbusDto, ByteBuf> {
    public static final String MOTOR_AFTER_SERVICE = "motorAfterService";

    /**
     * 1电机-状态1 2电机-状态2
     */
    public static String status1 = "00 00", status2 = "00 00";

    /**
     * 后置处理结果判断
     *
     * @param resp
     * @return
     */
    @Override
    public boolean afterResultJudge(AfterStrategyParam resp) {
        log.debug("执行MOTOR_AFTER_SERVICE motorAfterService");
        List<ModbusDto> list = resp.getNewData();
        //此处接收串口或网口客户端回应代码,并处理
        ModbusDto motorDto = list.get(0);
        String instruction = resp.getInstruction();
        //EventBusCenter.getEventBus().post(new CustomEvent(HexUtil.encodeHexStr(motorDto.getFullBuff())));
        EventBusCenter.getEventBus().post(resp);
        log.info("COM" + resp.getPortKey()  + "发送指令>>>>" + instruction + "<<<<<<<收到指令" + HexUtil.encodeHexStr(motorDto.getFullBuff()));
        switch (motorDto.getCmdType()) {
            case (byte) 0x03:// 读多个保持寄存器
                String[] hexArr = instruction.split(" ");
                //03 指令的 三四位代表读的寄存器地址
                String address = hexArr[2] + hexArr[3];
                if (address.equals("3200")) {
                    String motorStatus = getMotorStatus(motorDto);
                    if (!motorStatus.isEmpty()) {
                        String portKey = resp.getPortKey();
                        if (portKey.equals("1")) {
                            status1 = motorStatus;
                        } else if (portKey.equals("2")) {
                            status2 = motorStatus;
                        }
                    }
                    log.info("COM1电机状态字>>>" + status1);
                    log.info("COM2电机状态字>>>" + status2);
                } else {
                    log.info(address);
                }
                break;
            case (byte) 0x04:
                break;
            default:
                log.info("当前电机端口控制错误");
        }

        return true;
    }

    /**
     * 判断 读取 3200 状态字数据
     */
    public String getMotorStatus(ModbusDto modbusDto) {
        byte[] unitBuff = modbusDto.getUnitBuff();
        return HexUtil.encodeHexStr(unitBuff);
    }
}
